package com.aixingfu.sports;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aixingfu.sports.MVP.contract.UpApkContract;
import com.aixingfu.sports.MVP.presenter.UpApkPresenter;
import com.aixingfu.sports.Model.UpApkModel;
import com.aixingfu.sports.ui.activity.ApplyServicesActivity;
import com.aixingfu.sports.ui.activity.OrderListActivity;
import com.aixingfu.sports.ui.activity.SearchActivity;
import com.aixingfu.sports.utils.CXVersionCheckUtils;
import com.aixingfu.sports.view.UpApkDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.UpApkCodeUtil;
import com.orie.librarybase.utils.UserUtils;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//首页
@Route(path = "/main/MainActivity")
public class MainActivity extends BaseActivity implements UpApkContract.MyView, OnButtonClickListener, OnDownloadListener {

    @BindView(R.id.ll_outlogin)
    LinearLayout llOutlogin;
    @BindView(R.id.rl_buy_card)
    RelativeLayout rlBuyCard;
    @BindView(R.id.rl_member_services)
    RelativeLayout rlMemberServices;
    @BindView(R.id.ll_home_dialog)
    LinearLayout llHomeDialog;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rl_order_list)
    RelativeLayout rlOrderList;
    @BindView(R.id.rl_member_services_apply)
    RelativeLayout rlMemberServicesApply;
    private UpApkPresenter upApkPresenter;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/MainActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        tvName.setText("当前登录人：" + UserUtils.getUserName(MainActivity.this));
        upApkPresenter = new UpApkPresenter();
        upApkPresenter.attachView(this);
        getUpApk();
//        /**
//         * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗; 不设置会默认所有activity都可以显示弹窗;
//         */
//        Beta.canShowUpgradeActs.add(MainActivity.class);
//        Bugly.init(getApplicationContext(), "d6463fa19b", false);
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_outlogin, R.id.ll_home_dialog, R.id.rl_buy_card, R.id.rl_member_services,R.id.rl_order_list,R.id.rl_member_services_apply})
    public void onViewClicked(View view) {
        String organization = UserUtils.getOrganization(MainActivity.this);
        switch (view.getId()) {
            case R.id.ll_outlogin:
                setDialog();
                break;
            case R.id.ll_home_dialog:
                break;
            case R.id.rl_buy_card:
                if ("xiaoshou".equals(organization)) {
                    ElectronicContractActivity.startActivityByRoute();
                } else {
                    RxToast.normal(MainActivity.this, "只有销售才能购卡").show();
                }
                break;
            case R.id.rl_member_services:
                SearchActivity.startActivityByRoute();
                break;
            case R.id.rl_order_list:
                OrderListActivity.startActivityByRoute();
                break;
            case R.id.rl_member_services_apply:
                ApplyServicesActivity.startActivityByRoute();
                break;
        }
    }
    public void setDialog() {
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(MainActivity.this);
        rxDialogSureCancel.setTitle("提示");
        rxDialogSureCancel.setContent("确定要退出吗？");
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
                UserUtils.logout(MainActivity.this);
                LoginActivity.startActivityByRoute();
                finish();
            }
        });
        rxDialogSureCancel.show();
    }
    public void getUpApk(){
        if (upApkPresenter.isViewAttached()){
            HashMap<String,String> map = new HashMap<>();
            map.put("edition","1");
            upApkPresenter.getUpApk(map);
        }
    }
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            //do something.
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setUpApk(UpApkModel data) {
        try {
            if (data.getCode() == 1){
                //当所用app前版本号
                String  codeversin = getVersion();
                String type = data.getData().getType();
                String content = data.getData().getContent();
                String url = data.getData().getUrl();
                String lineVersion = data.getData().getVersion();
                int upcode = UpApkCodeUtil.compareVersion(lineVersion, codeversin);
                switch (upcode){
                    case 0:
                        break;
                    case 1:
                        //去弹窗提示用户
                        if ("1".equals(type)){
                            //强制更新
                            startUpdate(url,true,lineVersion,content);
                        }else if("0".equals(type)){
                            //非强制更新
                            startUpdate(url,false,lineVersion,content);
                        }
                        break;
                    case -1:
                        //去弹窗提示用户
                        if ("1".equals(type)){
                            //强制更新
                            startUpdate(url,true,lineVersion,content);
                        }else if("0".equals(type)){
                            //非强制更新
                            startUpdate(url,false,lineVersion,content);
                        }
                        break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }
    int versionCode = 0;
    @Override
    public Context getMyContext() {
        return this;
    }
    public String getVersion() {
        PackageInfo pkg;

        String versionName = "";
        try {
            pkg = MainActivity.this.getPackageManager().getPackageInfo(MainActivity.this.getApplication().getPackageName(), 0);
            versionCode = pkg.versionCode;
            versionName = pkg.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return versionName;
    }

    private DownloadManager manager;
    private void startUpdate(String url,boolean isUp,String codeName,String content) {
        /*
         * 整个库允许配置的内容
         * 非必选
         */
        UpdateConfiguration configuration = new UpdateConfiguration()
                //输出错误日志
                .setEnableLog(true)
                //设置自定义的下载
                //.setHttpManager()
                //下载完成自动跳动安装页面
                .setJumpInstallPage(true)
                //设置对话框背景图片 (图片规范参照demo中的示例图)
                //.setDialogImage(R.drawable.ic_dialog)
                //设置按钮的颜色
                //.setDialogButtonColor(Color.parseColor("#E743DA"))
                //设置按钮的文字颜色
                .setDialogButtonTextColor(Color.WHITE)
                //支持断点下载
                .setBreakpointDownload(false)
                //设置是否显示通知栏进度
                .setShowNotification(true)
                //设置是否提示后台下载toast
                .setShowBgdToast(false)
                //设置强制更新
                .setForcedUpgrade(isUp)
                //设置对话框按钮的点击监听
                .setButtonClickListener(this)
                //设置下载过程的监听
                .setOnDownloadListener(this);

        manager = DownloadManager.getInstance(this);
        manager.setApkName("sale.apk")
                .setApkUrl(url)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowNewerToast(true)
                .setConfiguration(configuration)
//                .setDownloadPath(Environment.getExternalStorageDirectory() + "/AppUpdate")
                .setApkVersionCode(versionCode+1)
                .setApkVersionName(codeName)
//                .setApkSize("20.4")
                .setAuthorities(getPackageName())
                .setApkDescription(content)
                .download();
    }

    @Override
    public void onButtonClick(int id) {

    }

    @Override
    public void start() {

    }

    @Override
    public void downloading(int max, int progress) {

    }

    @Override
    public void done(File apk) {

    }

    @Override
    public void cancel() {

    }

    @Override
    public void error(Exception e) {

    }
}
